import 'dart:convert';

import 'package:ble_demo/entity/smart_device.dart';
import 'package:ble_demo/pages/device_display_data.dart';
import 'package:ble_demo/pages/ecg_device_display_data.dart';
import 'package:ble_demo/pages/ecg_scan_device_page.dart';
import 'package:ble_demo/pages/scan_device_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ble_demo/ble/ble_plugin.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return OKToast(
        child: MaterialApp(
      title: '设备列表',
      theme: ThemeData(
        primaryColor: Colors.white,
      ),
      home: MyHomePage(title: '智能设备列表'),
      builder: EasyLoading.init(),
    ));
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<SmartDevice> _list = List();
  //设备本地存储器
  Future<SharedPreferences> _device_prefs = SharedPreferences.getInstance();
  @override
  void initState() {
    super.initState();
    // _list.add(SmartDevice(
    //     name: "Bioland-IT",
    //     deviceType: SmartDeviceType.BODY_GUN,
    //     displayName: "手持额温枪"));
    _list.add(SmartDevice(
        name: "iPhone",
        deviceType: SmartDeviceType.BODY_GUN,
        displayName: "手持额温枪",
        isStoreLocal: false));
    _list.add(SmartDevice(
        name: "FFFF3003030733",
        deviceType: SmartDeviceType.BODY_FAT,
        displayName: "智能体脂秤",
        isStoreLocal: false));
    _list.add(SmartDevice(
        name: "WeCardio UN+",
        deviceType: SmartDeviceType.BODY_WIFI_ECG,
        displayName: "无线心电仪",
        isStoreLocal: false));
    //请求权限
    _checkPermission(context);
  }

  _checkPermission(context) async {
    if (await Permission.location.isRestricted) {
      // The OS restricts access, for example because of parental controls.
      _showAlertDialog(context, "\“袋鼠健康\"想使用蓝牙", "通过蓝牙访问并控制智能设备", "好", "不允许");
    }
    if (await Permission.location.request().isGranted) {
      // Either the permission was already granted before or the user just granted it.

    }
  }

  /**
     * 弹出对话框
     *title: 袋鼠健康想要使用蓝牙
     * content :通过蓝牙访问并控制智能设备
     * yesText:好
     * noText:不允许
     */
  _showAlertDialog(context, title, content, yesText, noText) async {
    return await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: Text(title,
                  style: TextStyle(
                      color: Colors.black12,
                      fontSize: 18,
                      fontWeight: FontWeight.bold)),
              content: Text(content, style: TextStyle(color: Colors.grey)),
              actions: <Widget>[
                RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    color: Colors.deepOrange,
                    child: Center(
                      child: Text(noText,
                          style:
                              TextStyle(color: Colors.black12, fontSize: 18)),
                    ),
                    onPressed: () {}),
                RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10)),
                    color: Colors.deepOrange,
                    child: Center(
                      child: Text(yesText,
                          style: TextStyle(color: Colors.white, fontSize: 18)),
                    ),
                    onPressed: () {})
              ]);
        });
  }

  Future<bool> _hasDevicePrefs(String mac) async {
    SharedPreferences preferences = await _device_prefs;
    return preferences.containsKey(mac);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.title),
      ),
      body: Padding(
          padding: const EdgeInsets.all(10),
          child: ListView.builder(
              itemCount: _list.length,
              itemBuilder: (context, index) => _buildItem(context, index))),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          BlePlugin.scan();
        },
        backgroundColor: Colors.deepOrange,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  _buildItem(context, index) {
    SmartDevice device = _list[index];
    return SizedBox(
      height: 48,
      child: Card(
        color: Colors.deepOrange,
        child: GestureDetector(
          child: Row(
            children: [
              Expanded(
                  child: Center(
                child: Text(
                  device.name,
                  style: TextStyle(fontSize: 20, color: Colors.white),
                ),
              )),
              Icon(
                Icons.chevron_right,
                color: Colors.white,
                size: 36,
              )
            ],
          ),
          onTap: () {
            //判断是否已经存在本地
            _hasDevicePrefs(device.mac).then((hasDevice) {
              print("mac地址：${device.mac} ===是否存在本地===" + hasDevice.toString());
              if (hasDevice) {
                if (device.deviceType == SmartDeviceType.BODY_WIFI_ECG) {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => EcgDeviceDisplayData(device)));
                } else {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => DeviceDisplayData(device)));
                }
              } else {
                if (device.deviceType == SmartDeviceType.BODY_WIFI_ECG) {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => EcgScanDevicePage(device)));
                } else {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => ScanDevicePage(device)));
                }
              }
            });
          },
        ),
      ),
    );
  }
}
